<?php

/**
 * Albireo Kernel
 *
 * @copyright  Copyright (c) 2010 Albireo Solutions
 * @package    Kernel
 */

namespace WebModule;

use \Albireo\OAuth\OAuthClient;

use \Facebook;

/**
 * Sign In Page presenter.
 *
 * @author     Albireo Solutions
 * @package    Kernel
 */
class FacebookAppPresenter extends BasePresenter {


    private $facebook_sdk;

    public function __construct() {
        $oAuthClient = new OAuthClient(OAuthClient::FB);
        $credentials = $oAuthClient->getCredentials();
        $appInfo = array(
          'appId'  => $credentials["key"],
          'secret' => $credentials["secret"],
        );

        $this->facebook_sdk = new \Facebook($appInfo);
    }

    public function actionDefault() {
        
    }

    public function actionAppAccessToken() {
        $token = $this->facebook_sdk->getAccessToken();
        $this->getTemplate()->token = $token;
    }

    /**
     * Asks the user for the permission. The method ends by redirect to FB dialog.
     *
     * @throws \Exception
     * @return void
     */
    public function actionRequest() {

        $oAuthClient = new OAuthClient(OAuthClient::FB);
        $scope = array("offline_access", "email");
        $requestTokenInfo = $oAuthClient->getRequestTokenUri($this->link("//authorized"), $scope);
        $this->redirectUri($requestTokenInfo);

    }

    public function actionAuthorized(/* polymorphic */) {
        $params = $this->getHttpRequest()->getQuery();
        if (array_key_exists("error", $params)) {
            // the user has denied the access, fuck him
            \Nette\Debug::dump($params);
            throw new \Exception("an error occured, probably the user has denied access to his account");
        } elseif (array_key_exists("code", $params)) {

            $access_token = $this->facebook_sdk->getAccessTokenFromCode($params["code"]);
            $this->facebook_sdk->setAccessToken($access_token);
            $user = $this->facebook_sdk->api("/me"); // we assume the user is logged in
            
            \dibi::insert("fb_users_approved",
                array(
                    "uid" => $user["id"],
                    "first_name" => $user["first_name"],
                    "last_name" => $user["last_name"],
                    "code" => $params["code"],
                    "access_token" => $access_token,
            ))->execute();
            
            $this->flashMessage("We've got you. You can run but never hide. We know your name, your family, your hobbies, " . $user['first_name'] . "...");
            $this->flashMessage("use this if you want to get people lookup running: $access_token");

            $this->redirect("default");
        }

    }
    
}